package aa.jx.register.service;

import aa.jx.register.mapper.UserMapper;
import aa.jx.register.model.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.*;
import java.util.concurrent.ConcurrentHashMap;

@Service
public class UserServiceImpl implements UserSgervice {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private EmailService emailService;

    // 存储验证码和临时用户信息的缓存
    private final Map<String, String> verificationCodes = new ConcurrentHashMap<>();
    private final Map<String, User> tempUsers = new ConcurrentHashMap<>();

    @Override
    public Map<String, Object> sendVerificationCode(String email) {
        Map<String, Object> result = new HashMap<>();

        // 1. 验证邮箱格式
        if (!isValidEmail(email)) {
            result.put("success", false);
            result.put("message", "邮箱格式不正确");
            return result;
        }

        // 2. 检查邮箱是否已注册
        if (userMapper.isEmailExist(email) > 0) {
            result.put("success", false);
            result.put("message", "邮箱已注册");
            return result;
        }

        // 3. 生成并发送验证码
        String code = generateRandomCode();
        try {
            emailService.sendVerificationCode(email, code);

            // 存储验证码，10分钟后过期
            verificationCodes.put(email, code);
            scheduleCleanup(() -> verificationCodes.remove(email), 10 * 60 * 1000);

            result.put("success", true);
            result.put("message", "验证码已发送");
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "邮件发送失败: " + e.getMessage());
        }
        return result;
    }

    @Override
    public Map<String, Object> verifyEmail(String email, String code) {
        Map<String, Object> result = new HashMap<>();

        // 1. 检查验证码是否存在
        String savedCode = verificationCodes.get(email);
        if (savedCode == null) {
            result.put("success", false);
            result.put("message", "验证码已过期，请重新获取");
            return result;
        }

        // 2. 验证码比对
        if (!savedCode.equals(code)) {
            result.put("success", false);
            result.put("message", "验证码错误");
            return result;
        }

        // 3. 创建临时用户信息
        User tempUser = new User();
        tempUser.setEmail(email);
        tempUser.setRole(1); // 固定为普通用户
        tempUser.setDel(0);  // 未删除状态

        // 4. 生成token并存储临时用户
        String token = UUID.randomUUID().toString();
        tempUsers.put(token, tempUser);
        verificationCodes.remove(email);

        // 30分钟后过期
        scheduleCleanup(() -> tempUsers.remove(token), 30 * 60 * 1000);

        result.put("success", true);
        result.put("token", token);
        return result;
    }

    @Override
    public Map<String, Object> completeRegistration(String token, User userDetails) {
        Map<String, Object> result = new HashMap<>();

        // 1. 验证token有效性
        User tempUser = tempUsers.get(token);
        if (tempUser == null) {
            result.put("success", false);
            result.put("message", "会话已过期，请重新注册");
            return result;
        }

        // 2. 检查用户名是否已存在
        if (userMapper.isUsernameExist(userDetails.getUsername()) > 0) {
            result.put("success", false);
            result.put("message", "用户名已存在");
            return result;
        }

        // 3. 检查手机号是否已注册
        if (userMapper.isPhoneExist(userDetails.getPhone()) > 0) {
            result.put("success", false);
            result.put("message", "手机号已注册");
            return result;
        }
        // 3. 检查邮箱是否已注册
        if (userMapper.isEmailExist(userDetails.getEmail()) > 0) {
            result.put("success", false);
            result.put("message", "邮箱已注册");
            return result;
        }

        // 4. 设置用户完整信息（强制设置为普通用户）
        tempUser.setUsername(userDetails.getUsername());
        tempUser.setPassword(encryptPassword(userDetails.getPassword()));
        tempUser.setName(userDetails.getName());
        tempUser.setPhone(userDetails.getPhone());
        tempUser.setSex(userDetails.getSex());
        tempUser.setBirthday(userDetails.getBirthday());
        tempUser.setPayword(encryptPassword(userDetails.getPayword()));
        tempUser.setRole(1); // 强制设置为普通用户

        // 5. 保存到数据库
        try {
            int rows = userMapper.insert(tempUser);
            if (rows > 0) {
                tempUsers.remove(token);
                result.put("success", true);
                result.put("data", tempUser);
            } else {
                result.put("success", false);
                result.put("message", "注册失败，请重试");
            }
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "系统错误: " + e.getMessage());
        }

        return result;
    }
    @Override
    public Map<String, Object> adlogin(String phone, String password, Integer role) {
        Map<String, Object> result = new HashMap<>();

        // 1. 查询用户（改为用phone查询）
        User user = userMapper.selectByPhone(phone);
        if (user == null) {
            result.put("success", false);
            result.put("message", "手机号未注册");
            return result;
        }

        // 2. 验证密码
        if (!user.getPassword().equals(encryptPassword(password))) {
            result.put("success", false);
            result.put("message", "密码错误");
            return result;
        }

        // 3. 强制验证管理员角色
        if (user.getRole() != 2) {
            result.put("success", false);
            result.put("message", "您没有管理员权限");
            return result;
        }

        // 4. 检查用户状态
        if (user.getDel() == 1) {
            result.put("success", false);
            result.put("message", "账户已被禁用");
            return result;
        }

        // 5. 返回成功信息
        result.put("success", true);
        result.put("data", user.filterSensitiveInfo());
        return result;
    }

    @Override
    public Map<String, Object> login(String email, String password, Integer role)
    {
        Map<String, Object> result = new HashMap<>();

        // 1. 查询用户
        User user = userMapper.selectByEmail(email);
        if (user == null ){
            result.put("success", false);
            result.put("message", "邮箱未注册");
            return result;
        }

        // 2. 验证密码
        if
        (!user.getPassword().equals(encryptPassword(password))) {
            result.put("success", false);
            result.put("message", "密码错误");
            return result;
        }

        // 3. 验证角色
        if (role != null && !role.equals(user.getRole())) {
            result.put("success", false);
            result.put("message", "角色不匹配，请使用正确的登录入口");
            return result;
        }

        // 4. 检查用户状态
        if (user.getDel() == 1) {
            result.put("success", false);
            result.put("message", "账户已被禁用");
            return result;
        }

        // 5. 生成JWT token
        String token = generateJwtToken(user);

        // 6. 返回成功信息
        result.put("success", true);
        result.put("data", user.filterSensitiveInfo());
        result.put("token", token);
        return result;
    }

    // 生成JWT token的简单实现
    private String generateJwtToken(User user)
    {

        String header = Base64.getEncoder().encodeToString("{\"alg\":\"HS256\",\"typ\":\"JWT\"}".getBytes());
        String payload =
                Base64.getEncoder().encodeToString(
                        String.format(
                                "{\"sub\":\"%d\",\"name\":\"%s\",\"iat\":%d,\"exp\":%d}",
                                user.getId(),
                                user.getUsername(),
                                System.currentTimeMillis()/ 1000,
                                System.currentTimeMillis()/ 1000 + 3600 * 24
                        ).getBytes());
        String signature = DigestUtils.md5DigestAsHex((header + payload + "your-secret-key"
        ).getBytes());

        return header + "." + payload + "."
                + signature;
    }

    @Override
    public Map<String, Object> getUserInfo(Integer userId) {
        Map<String, Object> result = new HashMap<>();
        User user = userMapper.selectById(userId);
        if (user != null) {
            result.put("success", true);
            result.put("data", user.filterSensitiveInfo());
        } else {
            result.put("success", false);
            result.put("message", "用户不存在");
        }
        return result;
    }

    @Override
    public Map<String, Object> updateUserInfo(User user) {
        Map<String, Object> result = new HashMap<>();
        try {
            if (user.getId() <= 0) {
                result.put("success", false);
                result.put("message", "无效的用户ID");
                return result;
            }

            // 检查用户是否存在
            User existingUser = userMapper.selectById(user.getId());
            if (existingUser == null) {
                result.put("success", false);
                result.put("message", "用户不存在");
                return result;
            }
            int rows = userMapper.update(user);
            if (rows > 0) {
                result.put("success", true);
                result.put("message", "更新成功");
            } else {
                result.put("success", false);
                result.put("message", "更新失败，用户不存在");
            }
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "更新失败: " + e.getMessage());
        }
        return result;
    }




    // ========== 私有工具方法 ==========

    private String encryptPassword(String password) {
        return DigestUtils.md5DigestAsHex(password.getBytes());
    }

    private boolean isValidEmail(String email) {
        return email != null && email.matches("^[A-Za-z0-9+_.-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,}$");
    }

    private String generateRandomCode() {
        return String.valueOf(100000 + (int)(Math.random() * 900000));
    }

    private void scheduleCleanup(Runnable task, long delay) {
        new Timer().schedule(new TimerTask() {
            @Override
            public void run() {
                task.run();
            }
        }, delay);
    }
    @Override
    public Map<String, Object> updatePassword(Integer userId, String oldPassword, String newPassword) {
        Map<String, Object> result = new HashMap<>();

        try {
            // 1. 验证用户存在
            User user = userMapper.selectPasswordById(userId);
            if (user == null) {
                result.put("success", false);
                result.put("message", "用户不存在");
                return result;
            }

            // 2. 验证原密码是否正确
            if (!user.getPassword().equals(encryptPassword(oldPassword))) {
                result.put("success", false);
                result.put("message", "原密码不正确");
                return result;
            }

            // 3. 更新密码
            int rows = userMapper.updatePassword(userId, encryptPassword(newPassword));
            if (rows > 0) {
                result.put("success", true);
                result.put("message", "密码更新成功");
            } else {
                result.put("success", false);
                result.put("message", "密码更新失败");
            }
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "系统错误: " + e.getMessage());
        }

        return result;
    }

    @Override
    public Map<String, Object> updatePayword(Integer userId, String oldPayword, String newPayword) {
        Map<String, Object> result = new HashMap<>();

        try {
            // 1. 验证用户存在
            User user = userMapper.selectPaywordById(userId);
            if (user == null) {
                result.put("success", false);
                result.put("message", "用户不存在");
                return result;
            }

            // 2. 验证原支付密码是否正确
            if (!user.getPayword().equals(encryptPassword(oldPayword))) {
                result.put("success", false);
                result.put("message", "原支付密码不正确");
                return result;
            }

            // 3. 更新支付密码
            int rows = userMapper.updatePayword(userId, encryptPassword(newPayword));
            if (rows > 0) {
                result.put("success", true);
                result.put("message", "支付密码更新成功");
            } else {
                result.put("success", false);
                result.put("message", "支付密码更新失败");
            }
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "系统错误: " + e.getMessage());
        }

        return result;
    }
}